//
//  BKDevRootVC.m
//  BKDevMenu
//
//  Created by luzz on 2021/11/3.
//

#import "BKDevRootVC.h"
#import "BKDevMenuItem.h"


@interface BKDevHeader : UIView
@property (nonatomic, weak)UILabel *titleLabel;
@property (nonatomic, weak)UIButton *infoBtn;
@end

@implementation BKDevHeader

- (NSString *)getSDKVersion
{
    NSString *version;
    NSString *podspecPath = [[NSBundle mainBundle] pathForResource:@"BKDevMenu" ofType:@"podspec"];
    NSString *podspecStr = [[NSString alloc] initWithContentsOfFile:podspecPath encoding:NSUTF8StringEncoding error:NULL];
    NSArray *lines = [podspecStr componentsSeparatedByString:@"\n"];
    for (NSString *lineStr in lines) {
        if ([lineStr containsString:@"spec.version"]) {
            NSArray* words = [lineStr componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            NSString* nospacestring = [words componentsJoinedByString:@""];
            if ([nospacestring hasPrefix:@"spec.version"]) {
                NSScanner *scanner = [NSScanner scannerWithString:nospacestring];
                BOOL found;
                NSMutableArray * temp = [NSMutableArray array];
                while ([scanner isAtEnd] == NO) {
                    found = [scanner scanString:@"\"" intoString:NULL];
                    if (found) {
                        [temp addObject:@(scanner.scanLocation)];
                    }else{
                        scanner.scanLocation++;
                    }
                }
                if (temp.count >= 2) {
                    NSInteger start = [temp[0] integerValue];
                    NSInteger end = [temp[1] integerValue];
                    version = [nospacestring substringWithRange:NSMakeRange(start, end - start - 1)];
                    NSLog(@"version = %@",version);
                    break;
                }
            }
        }
    }
    return version;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        UILabel *titleLabel = [[UILabel alloc] init];
        NSString *appName = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleDisplayName"];
        titleLabel.text = [NSString stringWithFormat:@"%@开发人员控制台 v%@",appName,[self getSDKVersion]];
        titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15];
        titleLabel.textColor = [UIColor whiteColor];
        [self addSubview:titleLabel];
        self.titleLabel = titleLabel;
        

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        btn.tintColor = [UIColor whiteColor];
        [self addSubview:btn];
        self.infoBtn = btn;
    }
    return self;
}


- (void)layoutSubviews
{
    [super layoutSubviews];
    [self.titleLabel sizeToFit];
    self.titleLabel.center = CGPointMake(CGRectGetWidth(self.frame)/2, CGRectGetHeight(self.frame)/2);
    [self.infoBtn sizeToFit];
    self.infoBtn.center = CGPointMake(CGRectGetMaxX(self.titleLabel.frame) + 20, CGRectGetMidY(self.titleLabel.frame));
}

@end


@interface BKDevMenuCell : UITableViewCell
@property(nonatomic,strong)UISegmentedControl * segControl;
@end

@implementation BKDevMenuCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.backgroundColor = [UIColor clearColor];
        self.textLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15];
    }
    return self;
}
- (void)layoutSubviews
{
    [super layoutSubviews];
    if (self.segControl) {
        [self.segControl sizeToFit];
        CGSize segSize = self.segControl.frame.size;
        self.segControl.frame = CGRectMake(self.contentView.frame.size.width - 15 - segSize.width, (self.contentView.frame.size.height - segSize.height)/2, segSize.width, segSize.height);
    }
}

@end

@interface BKDevRootVC ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) BKDevHeader *headView;
@end

@implementation BKDevRootVC
@synthesize menuItem = _menuItem;
#define kHeaderHeight 50.0f
#define kCellHeight 50.0f
#define kMaxRowNum 6

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor clearColor];
    
    self.actionView = [[BKDevTransformView alloc] initWithFrame:CGRectMake(0, 0, kDevBtnWidth, kDevBtnWidth)];
    self.devBtn.frame = self.actionView.bounds;
    [self.actionView addSubview:self.devBtn];
    
    self.tableView.alpha = 0;
    [self.actionView addSubview:self.tableView];
    
    
    [self.view addSubview:self.actionView];
}
- (void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    self.tableView.frame = self.actionView.bounds;

}


-(CGFloat)listHeight
{
    CGFloat height = (self.menuItem.count <= kMaxRowNum?self.menuItem.count * kCellHeight:kCellHeight * kMaxRowNum) + kHeaderHeight;
    return MAX(kCellHeight, height);
    
}

    


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.minimizeActionBlock) {
        self.minimizeActionBlock();
    }
}


-(void)segAction:(UISegmentedControl *)seg
{
    NSInteger index = seg.accessibilityLabel.integerValue;
    if (index < self.menuItem.count ) {
        BKDevMenuItem * item = [self.menuItem objectAtIndex:index];
        if (item.segAction) {
            item.segAction(seg.selectedSegmentIndex, self.currentTopNav);
        }
    }
    
    seg.userInteractionEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.minimizeActionBlock) {
            self.minimizeActionBlock();
        }
    });
    
}


- (void)toAboutPageAction:(id)sender
{
    if (self.toAboutPageBlock) {
        self.toAboutPageBlock();
    }
}

#pragma mark - UITableViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat y = scrollView.contentOffset.y;
    
    if (y > kHeaderHeight) {
        self.headView.alpha = 0.0;
    }else if(y >=0 && y<= kHeaderHeight){
        self.headView.alpha = 1.0 - (1.0/kHeaderHeight) * y;
    }else{
        self.headView.alpha = 1.0;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return self.headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return kHeaderHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kCellHeight;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.menuItem.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BKDevMenuCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([BKDevMenuCell class])];
    
    
    if (indexPath.row < self.menuItem.count) {
        BKDevMenuItem * item = [self.menuItem objectAtIndex:indexPath.row];
        cell.textLabel.text = item.title;
        
        if (cell.segControl) {
            [cell.segControl removeFromSuperview];
            cell.segControl = nil;
        }
        
        switch (item.style) {
            case BKDevMenuItemStyleDefault:cell.textLabel.textColor = [UIColor whiteColor];
                break;
            case BKDevMenuItemStyleCancel:cell.textLabel.textColor = [UIColor lightGrayColor];
                break;
            case BKDevMenuItemStyleDestructive:cell.textLabel.textColor = [UIColor systemRedColor];
                break;
            case BKDevMenuItemStyleQuickLogin:
            {
                NSAttributedString *str1 = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"[快登] %@",item.title] attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:15],NSForegroundColorAttributeName:[UIColor systemBlueColor]}];
                NSAttributedString *str2 = [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@" %@",item.detail] attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:11],NSForegroundColorAttributeName:[UIColor colorWithWhite:0.93 alpha:1.0]}];
                NSMutableAttributedString *str = [[NSMutableAttributedString alloc] init];
                [str appendAttributedString:str1];
                [str appendAttributedString:str2];
                cell.textLabel.attributedText = str;
            }
                break;
            case BKDevMenuItemStyleSegment:{
                cell.textLabel.textColor = [UIColor whiteColor];
                
                cell.segControl = [[UISegmentedControl alloc] initWithItems:item.segments];
                cell.segControl.selectedSegmentIndex = item.defaultIndexBlock();
                cell.segControl.backgroundColor = [UIColor whiteColor];

                [cell.segControl setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:13],NSForegroundColorAttributeName:[UIColor darkGrayColor]} forState:UIControlStateNormal];
                [cell.segControl setTitleTextAttributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-SemiBold" size:14],NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateSelected];
                [cell.segControl addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
                cell.segControl.accessibilityLabel = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
                [cell.contentView addSubview:cell.segControl];
                
            }
                break;
            default:
                break;
        }
        
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (self.minimizeActionBlock) {
        self.minimizeActionBlock();
    }
    if (indexPath.row < self.menuItem.count) {
        BKDevMenuItem * item = [self.menuItem objectAtIndex:indexPath.row];
        if (item.action) {
            item.action(self.currentTopNav);
        }
        
    }
}

#pragma mark - lazy
- (UIButton *)devBtn
{
    if (!_devBtn) {
        _devBtn = [[UIButton alloc] init];
        _devBtn.backgroundColor = [UIColor clearColor];
        [_devBtn setAttributedTitle:[[NSAttributedString alloc] initWithString:@"DEV" attributes:@{NSFontAttributeName:[UIFont fontWithName:@"PingFangSC-Regular" size:15],NSForegroundColorAttributeName:[UIColor whiteColor]}] forState:UIControlStateNormal];
    }
    return _devBtn;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
        _tableView.separatorColor = [UIColor lightGrayColor];
        [_tableView registerClass:[BKDevMenuCell class] forCellReuseIdentifier:NSStringFromClass([BKDevMenuCell class])];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
    }
    return _tableView;
}

- (NSArray *)menuItem
{
    if (!_menuItem) {
        _menuItem = [NSArray array];
    }
    return _menuItem;
}
- (BKDevHeader *)headView
{
    if (!_headView) {
        _headView = [[BKDevHeader alloc] init];
        [_headView.infoBtn addTarget:self action:@selector(toAboutPageAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _headView;
}
@end
